package cn.xm.org.service.impl;

import cn.xm.basic.service.BaseService;
import cn.xm.basic.service.impl.BaseServiceImpl;
import cn.xm.basic.util.PageList;
import cn.xm.org.domain.Department;
import cn.xm.org.mapper.DepartmentMapper;
import cn.xm.org.query.DepartmentQuery;
import cn.xm.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.StyledEditorKit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.findAll();
        Map<Long, Department> parentMap = departments.stream().collect(Collectors.toMap(Department::getId, department -> department));
        List<Department> result = new ArrayList<>();
        for (Department dept:
             departments) {
            if (dept.getParentId() == null) {
                result.add(dept);
            } else {
                Department parent = parentMap.get(dept.getParentId());
                List<Department> children = parent.getChildren();
                children.add(dept);
//                for (Department parent:
//                     departments) {
//                    if (parent.getId().equals(dept.getParentId())) {
//                        parent.getChildren().add(dept);
//                        break;
//                    }
//                }
            }
        }
         return result;
    }
}
